package com.example.demo.controller;


import com.example.demo.pojo.param.DeleteFileParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/files")
public class FilesUpDownController {
    @Value("${file.upload-dir}")
    private String uploadDir;

    // 上传文件
    @PostMapping("/upload")
    public ResponseEntity<String> upload(MultipartFile file) {
        //
        String fileName = file.getOriginalFilename();
        log.debug("文件名={}", fileName);
        //2.获取图片后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //3.生成一个随机串作为新的图片名
        fileName = UUID.randomUUID() + suffix;
        //4.指定一个磁盘路径,作为保存图片文件的根路径
        //String dirPath = "d:/files/img";
        //5.为了提高检索性能,我们可以设置一颗日期格式生成对应的文件夹类存储图片文件
        //这里采用的是年月日的格式
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        //6.将当前真实的日期转为上面的格式
        String datePath = sdf.format(new Date());
        //7.将上面的磁盘路径与日期路径拼接成一个完整的图片文件存放路径
        File dirFile = new File(uploadDir + "/files" + datePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //8.拼接图片的完整路径
        String filePath = uploadDir + "/files" + datePath + fileName;
        log.debug("文件路径={}", filePath);
        try {
            // 将文件写入到指定路径下
            file.transferTo(new File(filePath));
            log.debug("下载路径是   files" + datePath + fileName);
//            return JsonResult.ok("/img" + datePath + fileName);
            return  ResponseEntity.ok("files" + datePath + fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 下载文件
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(String fileName) {
        try {
            log.debug("文件路径={}", fileName);
                //filename 里带路径可以直接解析
            Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();

            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() || resource.isReadable()) {
                //前端不处理下载流程需要设置请求头 如果前端使用 手动处理下载流程则不用使用 总之使用不会错
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "newFile.doc" + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }



    @PostMapping("/delete")
    public ResponseEntity<String> deleteFile(@RequestParam String fileName){
        // 获取文件的完整路径
        log.debug("文件路径={}", fileName);
        Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();

        try {
            // 删除文件
            Files.delete(filePath);
          return  ResponseEntity.ok("文件已成功删除: " + filePath);
        } catch (IOException e) {
          return  ResponseEntity.ok("删除文件时出错: " + e.getMessage());
        }
    }


}
